<?php

/**
 * Description of VirtualLabs_Admin_Machines
 *
 * @author markos
 */
class VirtualLabs_Admin_Usuario extends VirtualLabs_Admin_Dao {

    const PHRASE = '?/colita_virtual#par4Guay';
    const TABLE_NAME = 'usuario';
    const ROL_PROFESOR = 2;
    const ROL_ADMIN = 3;
    const ROL_ALUMNO = 1;

    private $debugLog;
    private $errorLog;

    public function __construct() {
        $this->debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $this->errorLog = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }

    public function getAlumnoByPattern($pattern) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $pattern = strtoupper("%$pattern%");
        $select = $db->select()
                ->from(array("u" => "usuario"), array('username', 'nombre', 'apellido', 'email'))
                ->where("tipo_usuario = ?", self::ROL_ALUMNO)
                ->where("upper(apellido) like ? or upper(email) like ? or upper(nombre) like ?");
        try {
            $this->debugLog->debug($select);
            $result = $db->fetchAll($select, array($pattern, $pattern, $pattern));
            return $result;
        } catch (Exception $e) {
            $this->errorLog->err($select);
            throw $e;
        }
    }

    public static function getPassword($passw) {
        $phrase = self::PHRASE . $passw;
        return md5(utf8_encode($phrase));
    }

    /**
     * 
     * @param type $fields
     * @param type $where
     * @return type
     * @throws Exception
     */
    public function getUsuarios($fields = array(), $where = array()) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()->from("usuario", $fields);
        foreach ($where as $key => $value) {
            $select->where("$key {$value['criteria']} ?", $value['value']);
        }

        try {
            return $db->fetchAll($select);
        } catch (Exception $e) {

            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    /**
     *
     * Change client's password by one provided by the client in the change password form.
     * 
     * @param type $username client's username.
     * @param type $password new password to be set.
     * @return type $count > 0 success
     */
    public function changePassword($username, $password) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $count = $db->update("usuario", array("passw" => $password), array("username" => $username));
        return $count;
    }

    public function loginForgotUsuario($key) {
        $db = Zend_Db_Table::getDefaultAdapter();
        try {
            $select = $db->select()->from('usuario', array('*'))->
                    where("email = ?", $key)->
                    orWhere("username = ?", $key);
            return $db->fetchRow($select);
        } catch (Exception $e) {
            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    /**
     * Based on the email address of a client and the password received in the confirmation message by the client
     * search client's information
     * 
     * @param type $hash password of the client
     * @param type $email client's mail address
     * @return type array including code, branch code and name.
     */
    public static function checkClientHash($hash, $email) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()
                ->from(array("B" => "DBCONEX.BROKEACC"), array("codigo" => "CLIID", "sucursal" => "CLISUC", "nombre", "CLINM"))
                ->where("B.EMAIL = ?", $email)
                ->where("B.PASSWD = ?", $hash);
        $result = $db->fetchRow($select);
        return $result;
    }

    /**
     *
     * Resets client's password based on a hash provided by the calling method.
     * 
     * @param type $password new hash
     * @param type $cliid client code
     * @param type $clisuc brach code
     * @return type $count > 0 success
     */
    public function generatePassword() {
        $generatedPassword = $this->generateRandomString();
        return $generatedPassword;
    }

    /**
     *
     * Resets client's password based on a hash provided by the calling method.
     * 
     * @param type $password new hash
     * @param type $cliid client code
     * @param type $clisuc brach code
     * @return type $count > 0 success
     */
    public function resetPassword($username, $password) {
        try {
            $debuglogger = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debuglogger->debug("[change-password] $username/$password");
            $data = array('passw' => self::getPassword($password));
            $where = array('key' => 'username', 'value' => $username);

            $this->save(self::TABLE_NAME, $data, $where);
        } catch (Exception $e) {
            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    private function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /**
     * 
     * @param type $fields
     * @param type $where
     * @return type
     * @throws Exception
     */
    public function getUsuario($fields = array(), $where = array()) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()->from("usuario", $fields);
        foreach ($where as $key => $value) {
            $select->where("$key {$value['criteria']} ?", $value['value']);
        }        
        try {
            return $db->fetchRow($select);
        } catch (Exception $e) {
            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    /**
     * Recupera los profesores
     * 
     */
    public function getProfesoresAsociados($fields = '*', $where = array()) {
        $db = Zend_Db_Table::getDefaultAdapter();
        try {
            $select = $db->select()->from(array("u" => "usuario"), array())->
                    //join(array("ur" => "usuario_rol"), "u.username = ur.username", $fields)->
                    join(array("ml" => "miembro_laboratorio"), "u.username = ml.username", $fields)->
                    where("u.tipo_usuario = ?", self::ROL_PROFESOR);

            foreach ($where as $key => $value) {
                $select->where("$key {$value['criteria']} ?", $value['value']);
            }
            $this->debugLog->debug($select);
            return $db->fetchAll($select);
        } catch (Exception $e) {
            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    public function getProfesoresNoAsociados($fields = '*', $where = array()) {
        $db = Zend_Db_Table::getDefaultAdapter();
        try {
            $select = $db->select()->from(array("u" => "usuario"), $fields)->
                    //join(array("ur" => "usuario_rol"), "u.username = ur.username", $fields)->
                    where("u.tipo_usuario = ?", self::ROL_PROFESOR);
            $this->debugLog->debug($select);
            foreach ($where as $key => $value) {
                $select->where("$key {$value['criteria']} ?", $value['value']);
            }
            return $db->fetchAll($select);
        } catch (Exception $e) {
            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }

    
    public function getUsuariosByVM($fields = array(), $where = array()) {
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()->from("maquina_virtual_usuario", $fields);
        foreach ($where as $key => $value) {
            $select->where("$key {$value['criteria']} ?", $value['value']);
        }

        try {
            return $db->fetchAll($select);
        } catch (Exception $e) {

            $this->errorLog->err($e->getMessage());
            $this->errorLog->err($e->getTraceAsString());
            throw $e;
        }
    }
}

?>
